#include "base/buffer.h"
#include <string>
using namespace Base;

CBuffer::CBuffer()
:m_pBuf(0),
 m_uBufSize(0)
{

}

CBuffer::CBuffer(CBuffer& buf)
{
    *this = buf;
}

CBuffer::~CBuffer()
{
    Clear();
}

unsigned char* CBuffer::GetNativeBuf()
{
    return m_pBuf;
}

bool CBuffer::Clear()
{
    if (m_pBuf)
    {
        delete []m_pBuf;
        m_pBuf = 0;
    }
    m_uBufSize = 0;
    return true;
}

bool CBuffer::IsEmpty() const
{
    return !m_uBufSize || !m_pBuf;
}

bool CBuffer::IsValid() const
{
    return m_uBufSize && m_pBuf;
}

unsigned int CBuffer::GetBufSize() const
{
    return m_uBufSize;
}

CBuffer& CBuffer::operator=(CBuffer& buf)
{
    Clear();
    if (buf.IsValid())
    {
        m_uBufSize = buf.m_uBufSize;
        m_pBuf = buf.m_pBuf;

        buf.m_uBufSize = 0;
        buf.m_pBuf = 0;
    }
    else
    {
        m_pBuf = 0;
        m_uBufSize = 0;
    }

    return *this;
}

void CBuffer::CopyFrom(unsigned char* pBuf, unsigned int uSize)
{
    Clear();

    if (pBuf && uSize)
    {
        m_uBufSize = uSize;
        m_pBuf = new unsigned char[m_uBufSize];
        memcpy_s(m_pBuf, m_uBufSize, pBuf, uSize);
    }
}
void CBuffer::CopyFrom(CBuffer& buf)
{
    Clear();

    if (buf.IsValid())
    {
        m_uBufSize = buf.GetBufSize();
        m_pBuf = new unsigned char[m_uBufSize];
        memcpy_s(m_pBuf, m_uBufSize, buf.GetNativeBuf(), m_uBufSize);
    }
}
void CBuffer::Attach(unsigned char* pBuf, unsigned int uSize)
{
    Clear();
    m_pBuf = pBuf;
    m_uBufSize = uSize;
}
unsigned char* CBuffer::Detach()
{
    unsigned char* pOutBuffer = m_pBuf;
    m_pBuf = 0;
    m_uBufSize = 0;
    return pOutBuffer;
}